from django.shortcuts import HttpResponse
from django.utils.deprecation import MiddlewareMixin
# from rest_framework_jwt.utils import jwt_decode_handler
import jwt,time
from jwt.exceptions import ExpiredSignatureError,DecodeError
from django.http import JsonResponse
from django.conf import settings
from rest_framework import status
from management.models import Operate_LogModel,PermissionModel

import re,datetime,json

# 导入封装redis
# from utils.redsi_con import redis_conn
from utils.ip_address.ip_info import CzIp

# 分页器
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage


# 路由中间件 RBAC 鉴权中间件
class MyRBAC(MiddlewareMixin):
    cz = CzIp()
    permission = PermissionModel.objects.filter(is_delete=False).all()

    # 处理请求
    def process_request(self,request):
        try:
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP

            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            print(f"访问ip {ip} 时间 {datetime.datetime.now()}")
            print(f"地址 {address} 设备 {facility}")

            path = request.path_info
            method = request.method.lower()  # GET = get
            print(method,path)

            if re.findall("login|image_code|mobile_code", path, re.I):
                return None

            token = request.headers.get("Authorization")
            print('token>>>', token)
            try:
                payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms=['HS256'])
                request.session["staff"] = payload
                print('payload>>>', payload)
            except ExpiredSignatureError:
                return JsonResponse({"code": 401, "message": "token过期"})
            except DecodeError:
                return JsonResponse({"code": 402, "message": "请重新登录"})

            staff_id = payload.get("id")
            print(f"访问用户{staff_id}")

            # 操作日志
            if method != "get":
                for i in self.permission:
                    per_method = i.path.split()[0]
                    per_path = i.path.split()[1]
                    if re.findall(per_path, path, re.I) and method == per_method:
                        Operate_LogModel.objects.create(name=i.name, staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                                        address=address, facility=facility)
        except Exception as e:
            print('错误e>>>', e)
            return JsonResponse({
                'code': status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": "服务器错误"
            })
